package com.example.routelink.gateway.filter;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.util.DateUtils;
import com.example.routelink.gateway.entity.ResultData;
import com.example.routelink.gateway.entity.ResultEnum;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

@Component
@Slf4j
public class PauseFilterGatewayFilterFactory extends BaseFilter<PauseFilterGatewayFilterFactory.Config> implements Ordered {

    public PauseFilterGatewayFilterFactory() {
        super(PauseFilterGatewayFilterFactory.Config.class);
    }

    private final String filterName = "服务停止";

    @Override
    public GatewayFilter apply(PauseFilterGatewayFilterFactory.Config config) {
        return (exchange, chain) -> {
            long startTime = System.currentTimeMillis();
            if (StrUtil.isEmpty(config.date)) {
                return chain.filter(exchange);
            }
            if (!config.date.contains("-")) {
                return chain.filter(exchange);
            }
            String date1 = config.date.split("-")[0];
            String date2 = config.date.split("-")[1];
            if (!DateUtils.isDate(date1) || !DateUtils.isDate(date2)) {
                return chain.filter(exchange);
            }
            if (DateUtil.isIn(DateUtil.date(), DateUtil.parse(date1), DateUtil.parse(date2))) {
                writeLog(filterName, startTime, "维护时间中 当前时间{} 配置时间{} ", DateUtil.date(), config.date);
                return response(exchange, ResultEnum.ErrPause);
            }
            return chain.filter(exchange);
        };
    }

    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE;
    }

    @Data
    public static class Config {
        private String date;
    }
}
